﻿using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Company.UI.Language
{
    /// <summary>
    /// 语言本地化管理器
    /// </summary>
    public class LanguageLocalizationManager
    {
        public List<ResourceDictionary> FindResourceDictionariesByAbsolutePath(ResourceDictionary rootDictionary, string targetAbsolutePath)
        {
            var result = new List<ResourceDictionary>();
            FindRecursively(rootDictionary, targetAbsolutePath, result);
            return result;
        }

        private void FindRecursively(ResourceDictionary dictionary, string targetAbsolutePath, List<ResourceDictionary> result)
        {
            if (dictionary.Source != null)
            {
                // 获取资源字典的绝对路径
                var absoluteUri = new Uri(dictionary.Source.ToString(), UriKind.RelativeOrAbsolute);
                if (absoluteUri.IsAbsoluteUri && absoluteUri.AbsoluteUri == targetAbsolutePath)
                {
                    result.Add(dictionary);
                }
            }
            // 递归遍历合并的资源字典
            foreach (var mergedDictionary in dictionary.MergedDictionaries)
            {
                FindRecursively(mergedDictionary, targetAbsolutePath, result);
            }
        }

        public List<ResourceDictionary> FindResourceDictionariesInApplication(string targetAbsolutePath)
        {
            var result = new List<ResourceDictionary>();
            if (Application.Current != null)
            {
                foreach (var dictionary in Application.Current.Resources.MergedDictionaries)
                {
                    FindRecursively(dictionary, targetAbsolutePath, result);
                }
            }
            return result;
        }
        /// <summary>
        /// 设置语言
        /// </summary>
        /// <param name="destination">目标语言类型</param>
        public void SetLanguage(LanguageType destinationalLanguageType)
        {
            switch (destinationalLanguageType)
            {
                case LanguageType.Chinese:
                    Application.Current.Resources.MergedDictionaries[0].MergedDictionaries[11].MergedDictionaries[0].Source = new Uri("pack://application:,,,/Company.UI;component/Language/CN.xaml");
                    break;
                case LanguageType.English:
                    Application.Current.Resources.MergedDictionaries[0].MergedDictionaries[11].MergedDictionaries[0].Source = new Uri("pack://application:,,,/Company.UI;component/Language/EN.xaml");
                    break;
                default:
                    Application.Current.Resources.MergedDictionaries[0].MergedDictionaries[11].MergedDictionaries[0].Source = new Uri("pack://application:,,,/Company.UI;component/Language/CN.xaml");
                    break;
            }
        }
    }
}
